import { DeleteOutlined } from '@ant-design/icons';
import { Button, Divider, Modal, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { type ActionType, EditableProTable } from '@ant-design/pro-table';
import type { PropertyItem, PropertyParams } from '@/services/develop/types';
import { getColumns } from './columns';
import { handleRemove, handleSetting } from './action';
import type { ProFormInstance } from '@ant-design/pro-form';
import { StepsForm } from '@ant-design/pro-form';

type PropertyProps = {
  modelId: string;
  data: PropertyItem[];
  open: boolean;
  changeOpen: (open: boolean) => void;
};

const Property: React.FC<PropertyProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<PropertyItem[]>([]);
  const [step, setStep] = useState<number>(0);
  const [data, setData] = useState<PropertyItem[]>([]);
  const formRef = useRef<React.MutableRefObject<ProFormInstance<any> | undefined>[]>([]);

  useEffect(() => {
    setData(
      props.data.map((value) => {
        if (value.validateType == '') {
          value.validateType = null;
        }
        return value;
      }),
    );
  }, [props.data]);

  // 遍历获取需要编辑的行
  const editableKeys = props.data.map((value) => value.id);

  const onChange = (record: PropertyItem, dataSource: PropertyItem[]) => {
    setData(dataSource);
  };

  const propertyView = (
    <EditableProTable<PropertyItem, PropertyParams>
      actionRef={actionRef}
      value={data}
      columns={getColumns(step)}
      rowKey="id"
      bordered
      recordCreatorProps={false}
      cardProps={{
        bodyStyle: {
          padding: '0',
        },
      }}
      editable={{
        type: 'multiple',
        editableKeys: editableKeys,
        actionRender: (row, config, defaultDoms) => {
          return [defaultDoms.delete];
        },
        onValuesChange: onChange,
      }}
      toolBarRender={() => [
        <Popconfirm
          key={'batch_remove'}
          disabled={selectedRowsState?.length == 0}
          title={'您确定要删除已选' + selectedRowsState?.length + '条属性数据吗？'}
          onConfirm={async () => {
            await handleRemove(selectedRowsState);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="Yes"
          cancelText="No"
        >
          <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
            <DeleteOutlined />
            删除
          </Button>
        </Popconfirm>,
      ]}
      rowSelection={{
        onChange: (_, selectedRows) => {
          setSelectedRows(selectedRows);
        },
      }}
    />
  );

  return (
    <StepsForm
      formMapRef={formRef}
      onCurrentChange={setStep}
      containerStyle={{
        width: '100%',
        height: '100%',
      }}
      stepsProps={{
        style: {
          marginTop: 0,
        },
      }}
      formProps={{
        validateMessages: {
          required: '此项为必填项',
        },
        onValuesChange: onChange,
      }}
      stepsFormRender={(dom: any, submitter: any) => {
        return (
          <Modal
            title="模型配置"
            width={1600}
            open={props.open}
            onCancel={() => {
              props.changeOpen(false);
            }}
            footer={[
              submitter,
              step < 4 && (
                <>
                  <Button
                    onClick={async () => {
                      handleSetting(props.modelId, data);
                    }}
                  >
                    保存
                  </Button>
                  <Button
                    onClick={async () => {
                      props.changeOpen(false);
                    }}
                  >
                    取消
                  </Button>
                </>
              ),
            ]}
            destroyOnClose
          >
            {dom}
          </Modal>
        );
      }}
      onFinish={async () => {
        handleSetting(props.modelId, data).then(() => props.changeOpen(false));
      }}
    >
      <StepsForm.StepForm key="0" title="基本信息">
        {step == 0 && propertyView}
      </StepsForm.StepForm>
      <StepsForm.StepForm key="1" title="数据类型">
        {step == 1 && propertyView}
      </StepsForm.StepForm>
      <StepsForm.StepForm key="2" title="前端配置">
        {step == 2 && propertyView}
      </StepsForm.StepForm>
      <StepsForm.StepForm key="3" title="表单校验">
        {step == 3 && propertyView}
      </StepsForm.StepForm>
      <StepsForm.StepForm key="4" title="扩展配置">
        {step == 4 && propertyView}
      </StepsForm.StepForm>
    </StepsForm>
  );
};

export default Property;
